<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { Edit, Delete, RefreshRight, VideoPlay, Plus, Setting, Refresh, Document, Operation, Download, Upload, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import ServiceEditDialog from '../components/ServiceEditDialog.vue'
import ScriptSettingDialog from '../components/ScriptSettingDialog.vue'
import ServiceLogs from '../components/ServiceLogs.vue'
import BatchOperations from '../components/BatchOperations.vue'
import { useServiceStore, type Service } from '../stores/services'

const serviceStore = useServiceStore()

const searchKeyword = ref('')
const statusFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = computed(() => serviceStore.services.length)
const showConfigInfo = ref(false)

// 对话框相关数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentService = ref<Service | undefined>(undefined)

// 脚本配置对话框相关数据
const scriptDialogVisible = ref(false)
const currentServiceForScript = ref<Service | undefined>(undefined)

// 日志查看相关数据
const logsVisible = ref(false)
const currentServiceForLogs = ref<Service | undefined>(undefined)

// 批量操作对话框
const batchOperationsVisible = ref(false)

const filteredServices = computed(() => {
  let result = serviceStore.services

  // 根据关键字过滤
  if (searchKeyword.value) {
    result = result.filter(service => 
      service.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  // 根据状态过滤
  if (statusFilter.value !== 'all') {
    result = result.filter(service => service.status === statusFilter.value)
  }

  return result
})

// 清除所有过滤条件
const clearFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = 'all'
}

// 分页大小变更处理函数
const handleSizeChange = (size: number) => {
  pageSize.value = size
}

const getStatusType = (status: string) => {
  return status === 'running' ? 'success' : 'danger'
}

const getStatusText = (status: string) => {
  return status === 'running' ? '运行中' : '已停止'
}

const handleRestart = (service: Service) => {
  ElMessageBox.confirm(`确定要重启"${service.name}"服务吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    serviceStore.restartService(service.id)
    ElMessage({
      type: 'success',
      message: `${service.name}重启成功`
    })
  }).catch(() => {})
}

const handleStop = (service: Service) => {
  ElMessageBox.confirm(`确定要停止"${service.name}"服务吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    serviceStore.stopService(service.id)
    ElMessage({
      type: 'success',
      message: `${service.name}停止成功`
    })
  }).catch(() => {})
}

const handleStart = (service: Service) => {
  ElMessageBox.confirm(`确定要启动"${service.name}"服务吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    serviceStore.startService(service.id)
    ElMessage({
      type: 'success',
      message: `${service.name}启动成功`
    })
  }).catch(() => {})
}

const handleEdit = (service: Service) => {
  isEdit.value = true
  currentService.value = { ...service }
  dialogVisible.value = true
}

const handleDelete = (service: Service) => {
  ElMessageBox.confirm(
    `确定要删除"${service.name}"服务吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    serviceStore.deleteService(service.id)
    ElMessage({
      type: 'success',
      message: `${service.name}删除成功`
    })
  }).catch(() => {})
}

const handleAddService = () => {
  isEdit.value = false
  currentService.value = {
    id: 0,
    name: '',
    description: '',
    path: '',
    port: 80,
    domain: '',
    status: 'stopped'
  }
  dialogVisible.value = true
}

const handleSaveService = (service: Service) => {
  if (isEdit.value) {
    // 更新服务
    serviceStore.updateService(service.id, service)
    ElMessage({
      type: 'success',
      message: `服务"${service.name}"更新成功`
    })
  } else {
    // 添加新服务
    const newId = serviceStore.addService(service)
    ElMessage({
      type: 'success',
      message: `新服务"${service.name}"添加成功`
    })
  }
}

const handleConfigScripts = (service: Service) => {
  currentServiceForScript.value = { ...service }
  scriptDialogVisible.value = true
}

// 修复TypeScript类型错误
interface ScriptData {
  serviceId: number;
  scripts: {
    start: string;
    stop: string;
    restart: string;
    status: string;
  };
}

const handleSaveScripts = ({ serviceId, scripts }: ScriptData) => {
  serviceStore.updateServiceScripts(serviceId, scripts)
  ElMessage({
    type: 'success',
    message: '脚本设置保存成功'
  })
}

const handleViewLogs = (service: Service) => {
  currentServiceForLogs.value = { ...service }
  logsVisible.value = true
}

const refreshServiceStatus = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在刷新服务状态...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    await serviceStore.refreshAllServices()
    ElMessage({
      type: 'success',
      message: '服务状态刷新成功'
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '服务状态刷新失败'
    })
  } finally {
    loading.close()
  }
}

const openBatchOperations = () => {
  batchOperationsVisible.value = true
}

const handleBatchOperationComplete = () => {
  refreshServiceStatus()
}

// 处理文件操作命令
const handleFileCommand = (command: string) => {
  switch (command) {
    case 'export':
      exportConfigToFile()
      break
    case 'import':
      importFromFile()
      break
    case 'reload':
      reloadConfigFile()
      break
  }
}

// 导出配置到JSON文件
const exportConfigToFile = () => {
  try {
    ElMessageBox.confirm(
      '确定要导出当前配置吗？导出的文件需要手动替换项目中的配置文件。',
      '导出配置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    ).then(() => {
      const success = serviceStore.saveToJsonFile()
      if (success) {
        ElMessage({
          type: 'success',
          message: '配置已成功导出，请手动替换项目中的config.json文件'
        })
        showConfigInfo.value = true
      } else {
        ElMessage({
          type: 'error',
          message: '导出配置文件失败'
        })
      }
    }).catch(() => {
      // 用户取消操作
    })
  } catch (error) {
    console.error('导出配置文件时出错:', error)
    ElMessage({
      type: 'error',
      message: '导出配置文件时出错'
    })
  }
}

// 从用户上传的文件导入配置
const importFromFile = async () => {
  try {
    ElMessageBox.confirm(
      '从文件导入将会覆盖当前配置，是否继续?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      const loading = ElLoading.service({
        lock: true,
        text: '正在导入配置...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        const success = await serviceStore.importFromUploadedFile()
        if (success) {
          ElMessage({
            type: 'success',
            message: '配置已成功从文件导入'
          })
          // 刷新服务状态
          refreshServiceStatus()
        } else {
          ElMessage({
            type: 'error',
            message: '导入配置文件失败'
          })
        }
      } catch (error) {
        console.error('导入配置文件时出错:', error)
        ElMessage({
          type: 'error',
          message: '导入配置文件时出错'
        })
      } finally {
        loading.close()
      }
    }).catch(() => {
      // 用户取消操作
    })
  } catch (error) {
    console.error('准备导入时出错:', error)
  }
}

// 重新加载配置文件
const reloadConfigFile = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载配置文件...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const success = await serviceStore.loadFromJsonFile()
    if (success) {
      ElMessage({
        type: 'success',
        message: '配置文件加载成功'
      })
      // 刷新服务状态
      refreshServiceStatus()
    } else {
      ElMessage({
        type: 'warning',
        message: '配置文件为空或未找到，使用现有数据'
      })
    }
  } catch (error) {
    console.error('加载配置文件时出错:', error)
    ElMessage({
      type: 'error',
      message: '加载配置文件失败'
    })
  } finally {
    loading.close()
  }
}

onMounted(() => {
  // 页面加载时刷新服务状态
  refreshServiceStatus()
})
</script>

<template>
  <div class="home-container">
    <div class="search-bar">
      <div class="search-controls">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索服务名称"
          class="search-input"
          prefix-icon="Search"
        >
        </el-input>
        <el-select v-model="statusFilter" placeholder="全部状态" class="status-filter">
          <el-option label="全部状态" value="all" />
          <el-option label="运行中" value="running" />
          <el-option label="已停止" value="stopped" />
        </el-select>
      </div>
      <div class="action-buttons">
        <el-button type="primary" :icon="Plus" @click="handleAddService">添加服务</el-button>
        <el-button type="info" :icon="Refresh" @click="refreshServiceStatus">刷新状态</el-button>
        <el-button type="warning" :icon="Operation" @click="openBatchOperations">批量操作</el-button>
      </div>
      <div class="file-operations">
        <el-dropdown @command="handleFileCommand" trigger="click">
          <el-button type="primary">
            文件操作 <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="export">导出配置</el-dropdown-item>
              <el-dropdown-item command="import">从文件导入</el-dropdown-item>
              <el-dropdown-item command="reload" divided>重新加载配置</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 显示空状态 -->
    <div v-if="!filteredServices.length" class="empty-state">
      <el-empty 
        description="暂无服务数据" 
        :image-size="200"
      >
        <template #description>
          <p>服务列表为空，请点击"添加服务"按钮创建新服务</p>
          <p v-if="searchKeyword || statusFilter !== 'all'" class="filter-tip">
            <el-tag size="small" type="info">提示</el-tag>
            当前正在使用过滤条件，可能有服务被过滤掉
          </p>
        </template>
        <el-button type="primary" @click="handleAddService">添加第一个服务</el-button>
        <el-button v-if="searchKeyword || statusFilter !== 'all'" @click="clearFilters">
          清除过滤条件
        </el-button>
      </el-empty>
    </div>

    <!-- 显示服务列表 -->
    <template v-else>
      <el-table :data="filteredServices" style="width: 100%" border fit>
        <el-table-column prop="name" label="服务名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="150" />
        <el-table-column prop="path" label="部署路径" min-width="200" />
        <el-table-column prop="port" label="端口" min-width="80" />
        <el-table-column prop="domain" label="域名" min-width="180" />
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="320" fixed="right" align="center">
          <template #default="scope">
            <div class="action-group">
              <el-button
                v-if="scope.row.status === 'running'"
                type="primary"
                :icon="RefreshRight"
                circle
                @click="handleRestart(scope.row)"
                title="重启"
              />
              <el-button
                v-if="scope.row.status === 'running'"
                type="danger"
                :icon="VideoPlay"
                circle
                @click="handleStop(scope.row)"
                title="停止"
              />
              <el-button
                v-if="scope.row.status === 'stopped'"
                type="success"
                :icon="VideoPlay"
                circle
                @click="handleStart(scope.row)"
                title="启动"
              />
              <el-button
                type="warning"
                :icon="Setting"
                circle
                @click="handleConfigScripts(scope.row)"
                title="配置脚本"
              />
              <el-button
                type="info"
                :icon="Document"
                circle
                @click="handleViewLogs(scope.row)"
                title="查看日志"
              />
              <el-button type="info" :icon="Edit" circle @click="handleEdit(scope.row)" title="编辑" />
              <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.row)" title="删除" />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalCount"
        @current-change="currentPage = $event"
        layout="prev, pager, next, sizes, total"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        class="pagination"
      />
    </template>
    
    <!-- 配置文件信息提示 -->
    <el-card class="config-info" v-if="showConfigInfo">
      <template #header>
        <div class="card-header">
          <span>配置文件信息</span>
          <el-button type="text" @click="showConfigInfo = false">关闭</el-button>
        </div>
      </template>
      <p>
        配置保存在项目的 <code>/src/resources/config.json</code> 文件中。
      </p>
      <p>
        当您点击"导出配置"时，系统会将配置下载为JSON文件。您需要手动将该文件替换项目中的配置文件以使更改永久保存。
      </p>
      <p>
        如果您想从外部导入配置，请点击"从文件导入"并选择一个有效的JSON配置文件。
      </p>
    </el-card>
    
    <!-- 服务编辑对话框 -->
    <ServiceEditDialog
      :visible="dialogVisible"
      :service="currentService"
      :is-edit="isEdit"
      @update:visible="dialogVisible = $event"
      @save="handleSaveService"
    />
    
    <!-- 脚本配置对话框 -->
    <ScriptSettingDialog
      :visible="scriptDialogVisible"
      :service="currentServiceForScript"
      @update:visible="scriptDialogVisible = $event"
      @save="handleSaveScripts"
    />
    
    <!-- 服务日志查看抽屉 -->
    <ServiceLogs
      :visible="logsVisible"
      :service="currentServiceForLogs"
      @update:visible="logsVisible = $event"
    />
    
    <!-- 批量操作对话框 -->
    <BatchOperations
      :visible="batchOperationsVisible"
      @update:visible="batchOperationsVisible = $event"
      @execution-complete="handleBatchOperationComplete"
    />
  </div>
</template>

<style scoped>
.home-container {
  padding: 20px;
  max-width: 100%;
  width: 100%;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.search-controls {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  flex: 2;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  flex: 2;
}

.search-input {
  min-width: 200px;
  max-width: 300px;
}

.status-filter {
  min-width: 120px;
  max-width: 150px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  width: 100%;
}

.file-operations {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.action-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

.empty-state {
  margin: 40px 0;
  text-align: center;
}

.filter-tip {
  margin-top: 10px;
  font-size: 0.9em;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.config-info {
  margin-top: 30px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

code {
  background-color: #f2f2f2;
  padding: 2px 5px;
  border-radius: 4px;
  font-family: monospace;
}

@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-controls, .action-buttons, .file-operations {
    width: 100%;
    justify-content: center;
  }
  
  .search-input, .status-filter {
    min-width: 100%;
  }
  
  .file-operations {
    margin-left: 0;
    justify-content: center;
  }
}
</style>
